<script lang="ts" setup>

import { ref } from 'vue'

import { Plus } from '@element-plus/icons-vue'
import {baseInfoUpdateAvatarSerive} from '@/api/baseInfo.js'
import type { UploadProps ,FormItemProps, FormProps} from 'element-plus'
import { useUserStore } from '@/stores'
import { baseURL } from '@/utils/request' 
const uploadSelect= ref() 
const userStore = useUserStore()
const PMimgUrl = baseURL +  userStore.userInfo.img_url
const imageUrl = ref(PMimgUrl)
const img_url = ref('')

const labelPosition = ref<FormProps['labelPosition']>('right')
const handleAvatarSuccess: UploadProps['onSuccess'] = (uploadFile) => {

    // // 基于FileReader读取图片做预览(base64格式数据)
    // const reader = new FileReader()
    // reader.readAsDataURL(uploadFile.raw)
    // reader.onload = ()=>{
    //   imageUrl.value = reader.result
    // }
     img_url.value = uploadFile.raw
     imageUrl.value = URL.createObjectURL(uploadFile.raw) 
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const submit = async()=>{

    if (!img_url.value) {
     ElMessage.warning('请先选择图片！')
    return;
  }
  const fd = new FormData()
  fd.append('img_url',img_url.value)

   await baseInfoUpdateAvatarSerive(fd)
   userStore.getUserinfo()
   ElMessage.success('更新头像成功！')

}


</script>

<template>
  <div class="wrapped">
    <el-card>

   
    <div class="wrapped_content">


    <el-form-item>
    <el-upload
    ref="uploadSelect"
    class="avatar-uploader"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :on-change="handleAvatarSuccess"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
    </el-form-item>
  <el-form-item class="btn">
  <el-button type="primary" @click="uploadSelect.$el.querySelector('input').click()">上传</el-button>
  <el-button type="primary" @click="submit">保存</el-button>
  </el-form-item>
    </div>
     </el-card>
  </div>
</template>


<style lang="scss" scoped>
.wrapped_content{
  margin: 20px 20px ;
  height: 550px;
}

.avatar-uploader .avatar {
  width: 300px;
  height: 300px;
  display: block;
}
</style>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 300px;
  text-align: center;
}
.btn{
  margin: 40px 70px;
  .el-button{
    margin-right:10px ;
  }
}
</style>